package com.ddstation.app.api.controller;

import com.ddstation.app.api.model.MaInvsBaseDrugModel;
import com.ddstation.app.api.service.OpenApiService;
import com.ddstation.common.util.CheckUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller @Lazy
public class OpenApiController {

	@Inject private OpenApiService openApiService;

	/**
	 * 根据药品名称获取核心药品数据
	 * @param name
	 * @param specification
	 * @param manufacturer
	 * @return
	 */
	@RequestMapping(value="appinvs_open_api.do/search", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Object> invsOpenApiSearchEvent(@RequestParam String name,
			@RequestParam String specification,
			@RequestParam String manufacturer) {
		name = URLDecoder.decode(name);
		specification = URLDecoder.decode(specification);
		manufacturer = URLDecoder.decode(manufacturer);
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (CheckUtil.isEmpty(name)) {
			return retMap;
		}
		List<MaInvsBaseDrugModel> modelList = openApiService.select(name,specification,manufacturer);
		if (modelList.size() <= 0) {
			//药品名称+规格
			modelList = openApiService.select(name,specification,null);
			if (modelList.size() > 0) {	//参数传入的厂商无该药，但数据库有其他厂商的
				retMap.put("data", modelList);
				retMap.put("errCode", 1);
			} else {
				//药品名称+规格 匹配不到处理
				modelList = openApiService.select(name,null,null);
				if (modelList.size() > 0) {	//参数传入的规格无该药，但数据库有其他规格的
					retMap.put("data", modelList);
					retMap.put("errCode", 2);
				} else {
					retMap.put("errCode", 3);
				}
			}
		} else {
			retMap.put("data", modelList);
			retMap.put("errCode", 0);
		}
		return retMap;
	}
}
